package spring.boot.adminx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import spring.boot.adminx.model.SysMenu;
import spring.boot.adminx.model.SysRole;
import spring.boot.adminx.model.SysRoleMenu;
import spring.boot.adminx.service.SysMenuService;
import spring.boot.adminx.service.SysRoleMenuService;
import spring.boot.adminx.service.SysRoleService;
import spring.boot.adminx.utils.PageUtils;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/sys/role")
public class SysRoleController {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    /** 分页查询 */
    @GetMapping("list")
    @PreAuthorize("hasRole('SYS_ROLE_LIST')")
    public String list(Model model, String role,Integer pageNum, Integer pageSize){
        if (pageNum==null){
            pageNum = 1;
        }
        if (pageSize==null){
            pageSize = PageUtils.PAGE_SIZE;
        }
        Page<SysRole> page = new Page<>(pageNum,pageSize);
        QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
        if (role!=null&&role.trim().length()>0){
            wrapper.like("role",role);
            model.addAttribute("roleName",role);
        }
        IPage<SysRole> rolePage = sysRoleService.page(page, wrapper);
        model.addAttribute("pages",rolePage);

        List<Long> beforePages = new ArrayList<>();
        List<Long> afterPages = new ArrayList<>();
        PageUtils.page(rolePage.getPages(),rolePage.getCurrent(),beforePages,afterPages);
        model.addAttribute("beforePages",beforePages);
        model.addAttribute("afterPages",afterPages);

        return "system/role/list";
    }


    /** 启用停用 */
    @PostMapping("enable/{id}/{enable}")
    @ResponseBody
    @PreAuthorize("hasRole('SYS_ROLE_ENABLE')")
    public boolean enable(@PathVariable String id, @PathVariable String enable){
        UpdateWrapper<SysRole> wrapper = new UpdateWrapper<>();
        wrapper.set("enable",enable);
        wrapper.eq("id",id);
        return sysRoleService.update(wrapper);
    }

    @GetMapping("to/add")
    @PreAuthorize("hasRole('SYS_ROLE_ADD')")
    public String toAdd(){
        return "system/role/add";
    }

    @PostMapping("insert")
    @ResponseBody
    @PreAuthorize("hasRole('SYS_ROLE_ADD')")
    public String insert(String role){
        SysRole sysRole = new SysRole();
        sysRole.setId(IdWorker.getId());
        sysRole.setRole(role);
        sysRole.setEnable(1);
        if (sysRoleService.save(sysRole)){
            return "true";
        }else{
            return "保存失败";
        }
    }

    @GetMapping("to/update/{id}")
    @PreAuthorize("hasRole('SYS_ROLE_UPDATE')")
    public String toUpdate(@PathVariable String id, Model model){
        SysRole sysRole = sysRoleService.getById(id);
        model.addAttribute("sysRole",sysRole);
        return "system/role/edit";
    }

    @PostMapping("update")
    @ResponseBody
    @PreAuthorize("hasRole('SYS_ROLE_UPDATE')")
    public String update(String id,String role){
        SysRole sysRole = new SysRole();
        sysRole.setId(Long.valueOf(id));
        sysRole.setRole(role);
        if (sysRoleService.updateById(sysRole)){
            return "true";
        }else{
            return "保存失败";
        }
    }

    @GetMapping("to/update/menu/{id}")
    @PreAuthorize("hasRole('SYS_ROLE_MENU_UPDATE')")
    public String toUpdateMenu(@PathVariable String id, Model model){
        model.addAttribute("id",id);
        QueryWrapper<SysRoleMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("sys_role_id",id);
        List<SysRoleMenu> sysRoleMenus = sysRoleMenuService.list(wrapper);
        List<Long> menuIds = new ArrayList<>();
        for (SysRoleMenu roleMenu : sysRoleMenus) {
            menuIds.add(roleMenu.getSysMenuId());
        }

        List<SysMenu> menus = sysMenuService.selectTreeMenus(menuIds);
        model.addAttribute("menus", menus);


        List<String> menuIdsString = new ArrayList<>();
        for (Long menuId : menuIds) {
            menuIdsString.add(String.valueOf(menuId));
        }
        model.addAttribute("menuIds", menuIdsString);
        return "system/role/editMenus";
    }

    @PostMapping("menu/update")
    @ResponseBody
    @PreAuthorize("hasRole('SYS_ROLE_MENU_UPDATE')")
    public String roleUpdate(String id, String nodes){
        if (id==null||id.trim().length()<=0){
            return "参数id错误";
        }
        UpdateWrapper<SysRoleMenu> delWrapper = new UpdateWrapper<>();
        delWrapper.eq("sys_role_id",id);
        sysRoleMenuService.remove(delWrapper);
        if (nodes==null||nodes.trim().length()<=0){
            return "1";
        }
        String[] menuIds = nodes.split("_");
        List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
        for (String menuId : menuIds) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setSysMenuId(Long.valueOf(menuId));
            sysRoleMenu.setSysRoleId(Long.valueOf(id));
            sysRoleMenus.add(sysRoleMenu);
        }
        if (sysRoleMenuService.saveBatch(sysRoleMenus)) {
            return "1";
        }
        return "保存失败";
    }
}


